package com.example.firstdemo.ui.screens.pages.addProblem.addProblem.selectCarriage

import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavOptions
import androidx.navigation.compose.composable
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable

@Serializable
object SelectCarriage

fun NavGraphBuilder.selectCarriageDestination(
    padding: PaddingValues = PaddingValues(0.dp),
    navController: NavController
) {
    composable<SelectCarriage> {
        val viewModel: SelectCarriageViewModel = viewModel()
        val uiState = viewModel.uiState.collectAsStateWithLifecycle().value
        SelectCarriageScreen(
            padding = padding,
            uiState = uiState,
            onBack = navController::popBackStack,
            onGetCarriageList = viewModel::getCarriageList,
            onFilterCarriage = viewModel::filterCarriage,
            onSelectCarriage = {
                CoroutineScope(Dispatchers.IO).launch {
                    SelectCarriageEvent.emit(it)
                    withContext(Dispatchers.Main) {
                        navController.popBackStack()
                    }
                }
            }
        )
    }
}

fun NavController.navigateToSelectCarriage(navOptions: NavOptions? = null) {
    navigate(SelectCarriage, navOptions)
}